package com.haoshuang.zhouzhoubang.ui.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.databinding.ActivityBalanceWithdrawalBinding
import com.haoshuang.zhouzhoubang.model.bean.WithdrawableBean
import com.haoshuang.zhouzhoubang.model.bean.YeBean
import com.haoshuang.zhouzhoubang.ui.adapter.WithdrawableAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.TisJbDialog
import com.haoshuang.zhouzhoubang.ui.vm.BalanceWithdrawalViewModel
import com.haoshuang.zhouzhoubang.utils.PreferenceUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setEmptyData
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.core.setupData
import com.mufeng.libs.core.setupEmptyData
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.vertical
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone

import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import okhttp3.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat


/**
 *  余额提现界面
 */
class BalanceWithdrawalActivity :
    BaseVMActivity<BalanceWithdrawalViewModel, ActivityBalanceWithdrawalBinding>() {

    // 需要扣除的违规费用

    private var deduction_money_info: YeBean.DeductionMoneyInfo? = null
    private val data = arrayListOf<WithdrawableBean.WithdrawableList>()
    private val adapter = WithdrawableAdapter(data)

    private var isAllCheck = false

    override fun initView(savedInstanceState: Bundle?) {
        binding.apply {
            appBar.ivBack.clickWithTrigger { finish() }
            appBar.tvTitle.text = "余额提现"
            appBar.tvRight.visible()
            appBar.tvRight.text = "明细"
            appBar.tvRight.clickWithTrigger {
                startPage<BalanceWithdrawalDetailActivity>()
            }
            imageView16.clickWithTrigger {
                imageView16.setImageResource(R.mipmap.dz_ok)
                ivZfb.setImageResource(R.mipmap.dz_wx)
                extract_type = "weixin"
            }
            ivZfb.clickWithTrigger {
                ivZfb.setImageResource(R.mipmap.dz_ok)
                imageView16.setImageResource(R.mipmap.dz_wx)
                extract_type = "alipay"
            }

            allPrice.click {
                XPopup.Builder(mActivity)
                    .asCustom(ConfirmDialog(
                        context =mActivity,
                        title = "温馨提示",
                        content = "违规金额：指订单在服务中，未达到服务标准或其他服务原\n因导致，所扣除金额未进行处理。申请提现时需进行抵扣。",
                        cancelStr = "",
                        confirmStr = "我知道了",
                        isHideCancel = true,
                        isHideAgain = false,
                        onCancel = {},
                        onConfirm = {}))
                    .show()
            }

            recyclerView.vertical().adapter = adapter
            adapter.setEmptyData(R.mipmap.icon_empty_money, "暂无可提现金额")
            adapter.setOnItemClick { view, position,  item ->
                val item = adapter.getItem(position)
                if (item?.is_withdraw == 0)return@setOnItemClick
                var isAll = true
                data[position].isChecked = !data[position].isChecked
                data.filter { it.is_withdraw == 1 }.forEach {
                    if (!it.isChecked) {
                        isAll = false
                    }
                }
                isAllCheck = isAll
                adapter.notifyDataSetChanged()
                ivAllCheck.isSelected = isAllCheck
                sumTotal()
            }

            ivAllCheck.clickWithTrigger {
                isAllCheck = !isAllCheck
                ivAllCheck.isSelected = isAllCheck
                data.forEach {
                    if (it.is_withdraw == 1) {
                        it.isChecked = isAllCheck
                    }else{
                        it.isChecked = false
                    }
                }
                adapter.notifyDataSetChanged()
                sumTotal()
            }

            cbAllCheck.clickWithTrigger {
                isAllCheck = !isAllCheck
                ivAllCheck.isSelected = isAllCheck
                data.forEach { it.isChecked = isAllCheck }
                adapter.notifyDataSetChanged()
                sumTotal()
            }

            refreshLayout.setOnRefreshListener {
                isShowing = false
                p = 1
                vm.getNotWithdrawList(p)
            }

            refreshLayout.setOnLoadMoreListener {
                isShowing = false
                p++
                vm.getNotWithdrawList(p)
            }

            clickableEntryView.setOnClickListener {
                if (wechat_is_bind == 1) {
                    XPopup.Builder(this@BalanceWithdrawalActivity)
                        .asCustom(TisJbDialog(this@BalanceWithdrawalActivity, "") {
                            vm.getData4()
                        }).show()
                } else {

                    PreferenceUtils.putString("wx_type", "1")
                    val mWxApi = WXAPIFactory.createWXAPI(
                        this@BalanceWithdrawalActivity,
                        Config.WX_ID,
                        false
                    )
                    // 将该app注册到微信
                    mWxApi.registerApp(Config.WX_ID)
                    if (!mWxApi.isWXAppInstalled) {
                        toast("微信未安装,请先安装微信")

                    } else {
                        val req = SendAuth.Req()
                        req.scope = "snsapi_userinfo"
                        req.state = "diandi_wx_login"
                        mWxApi.sendReq(req)
                    }
                }


            }
            cevBindAlipay.setOnClickListener {
                if (zfb_is_bind == 1) {
                    XPopup.Builder(this@BalanceWithdrawalActivity)
                        .asCustom(
                            TisJbDialog(
                                this@BalanceWithdrawalActivity,
                                ""
                            ) {
                                vm.cancelBindAlipay()
                            }).show()
                } else {
                    startPage<BindAlipayActivity>()
                }


            }

            // 点击查看违规列表
            llDeductMoney.clickWithTrigger {
                startPage<ViolationDeductMoneyOrderListActivity>("id" to deduction_money_info?.bill_ids)
            }
        }
    }

    /**
     * 计算总提现金额
     */
    private fun sumTotal() {

        val list = data.filter { it.isChecked && it.is_withdraw == 1}
        if (list.isEmpty()){
            binding.editTextNumber.text = "0.00"
            return
        }
        billIds = list.joinToString(",") { it.bill_ids.toString() }
        var sum = 0.0
        list.forEach {
            sum += (it.balance?.toDoubleOrNull() ?: 0.0) * 100
        }
        val decimalFormat = DecimalFormat("#.02")
        val big = (sum - (deduction_money_info?.balance?.toDoubleOrNull() ?: 0.0) * 100) / 100f

        if (big != 0.0) {
            binding.editTextNumber.text = BigDecimal.valueOf(big).setScale(2, RoundingMode.HALF_UP).toString()
        } else {
            binding.editTextNumber.text = "0.00"
        }


    }

    override fun onRestart() {
        super.onRestart()
        vm.getData2()
    }

    private var yeBean: YeBean? = null
    var alipay_name = ""
    var alipay_code = ""
    private fun getAccessToken(code: String) {
        //获取授权
        val loginUrl = StringBuffer()
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
            .append("?appid=")
            .append(Config.WX_ID)
            .append("&secret=")
            .append("42d7b39540a16e20877ce7fc3b2e4e38")//4ca254cf0b05ad43f8730de3103e2d94
            .append("&code=")
            .append(code)
            .append("&grant_type=authorization_code")
        Log.d("urlurl", loginUrl.toString())

        val okHttpClient = OkHttpClient()
        val request = Request.Builder()
            .url(loginUrl.toString())
            .get()//默认就是GET请求，可以不写
            .build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("WXPay", "onFailure: 获取失败")

            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                val responseInfo = response.body!!.string()
                Log.d("fan12", "onResponse: $responseInfo")

                try {
                    val jsonObject = JSONObject(responseInfo)
                    var access = jsonObject.getString("access_token")
                    var openId = jsonObject.getString("openid")
                    Log.e("WXPay", "access: $access")
                    Log.e("WXPay", "openId: $openId")
                    runOnUiThread {
                        vm.getData3("openid" to openId)
                    }

                } catch (e: JSONException) {
                    e.printStackTrace()

                    Log.e("WXPay", "onFailure: 获取失败" + e.message)
                }
            }
        })
    }

    var extract_type = "weixin"

    private var billIds = ""
    override fun initData() {
        var price = intent.getStringExtra("price")

        binding.tvCommit.clickWithTrigger {
            var money = binding.editTextNumber.text.toString()
            if (billIds.isEmpty()) {
                toast("请选择提现日期")
                return@clickWithTrigger
            }
            if (extract_type == "weixin") {
                if (money.toDouble() > 500) {
                    toast("微信单笔提现金额最高500元")
                    return@clickWithTrigger
                }
            }
            // 判断是否绑定账号  微信和支付宝
            if (wechat_is_bind == 0 && extract_type == "weixin") {
                toast("没有绑定微信, 请先绑定微信")
                return@clickWithTrigger
            }
            if (zfb_is_bind == 0 && extract_type == "alipay") {
                toast("没有绑定支付宝, 请先绑定支付宝")
                return@clickWithTrigger
            }
            vm.getData("bill_ids" to billIds, "extract_type" to extract_type)
        }
        vm.getData2()
        // 获取可提现列表
        p = 1
        vm.getNotWithdrawList(p)
    }

    var wechat_is_bind = 0
    var zfb_is_bind = 0
    override fun startObserve() {
        LiveEventBus.get("Wxs", String::class.java).observe(this) {
            getAccessToken(it)
        }

        vm.getNotWithdrawListData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                binding.refreshLayout.setupEmptyData(data, adapter, p)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.setupData(it?.list, data, adapter, p)
                sumTotal()
            }
        }

        vm.getData4.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("解绑成功")
                wechat_is_bind = 0
                binding.clickableEntryView.setText("未绑定")
            }
        }

        /**
         * 支付宝解绑
         */
        vm.cancelBindAlipay.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("解绑成功")
                zfb_is_bind = 0
                binding.cevBindAlipay.setText("未绑定")
            }
        }
        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("绑定成功")
                wechat_is_bind = 1
                binding.clickableEntryView.setText("已绑定")
            }
        }
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                yeBean = it
                binding.textView45.text = "提现手续费${it?.cash_out_rate}%"
                deduction_money_info = it?.deduction_money_info
                binding.llDeductMoney.visibleOrGone(
                    (it?.deduction_money_info?.balance?.toDoubleOrNull() ?: 0.0) > 0
                )
                binding.tvDeductMoney.text = "您有${it?.deduction_money_info?.balance}元违规金额未处理"

                if (it?.alipay_name.isNullOrBlank()) {
                    binding.cevBindAlipay.setText("未绑定")
                    zfb_is_bind = 0
                } else {
                    zfb_is_bind = 1
                    alipay_name = it?.alipay_name!!
                    alipay_code = it?.alipay_code!!
                    binding.cevBindAlipay.setText(it?.alipay_name!! + "|解绑")
                }
                wechat_is_bind = it?.wechat_is_bind!!
                if (it?.wechat_is_bind == 0) {
                    binding.clickableEntryView.setText("未绑定")

                } else {
                    binding.clickableEntryView.setText("已绑定|解绑")
                }
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("提现申请已提交,请等待审核")
                // 体现金额
                val money = binding.editTextNumber.text.toString()
                // 提现方式
                // 服务费
                val rate = (yeBean?.cash_out_rate?.toDoubleOrNull() ?: 0.0) / 100
                val serviceMoney = money.toDouble() * rate
                // 实际到账金额
                val finishMoney =
                    BigDecimal(money.toDouble() - serviceMoney).setScale(2, RoundingMode.FLOOR)

                startPage<YueEeActivity>(
                    "money" to it?.extract_price.toString(),
                    "extract_type" to if (extract_type == "weixin") "微信" else "支付宝",
                    "deduction_money" to it?.liquidated_damages.toString(),
                    "serviceMoney" to it?.deductionmoney.toString(),
                    "finishMoney" to it?.realmoney.toString()
                )
                finish()
            }
        }
    }

}